import { omit } from 'lodash-es'
import { SvgConfig, SvgOutputType } from '../type'

const _genertateElements = (config: SvgConfig) => {
  const { components } = config
  const componentElements = components.map(component => {
    const omitedComponent = omit(component, ['id', 'type'])
    const props = Object.keys(omitedComponent).map(prop => {
      return ` ${prop}="${omitedComponent[prop]}"`
    }).join(' ')
    return `\n  <${component.type}${props} />`
  })
  return componentElements
}

export const convertToHtml = (config: SvgConfig) => {
  return (
`<svg viewBox="0 0 1024 1024">${_genertateElements(config)}
</svg>`
  )
}

export const convertToSymbol = (config: SvgConfig) => {
  return (
`<symbol id="${config.baseConfig.name}" viewBox="0 0 1024 1024">${_genertateElements(config)}
</symbol>`
  )
}

export const convertToJson = (config: SvgConfig) => {
  return JSON.stringify(config, null, 2)
}

const convertMap = {
  HTML: convertToHtml,
  SYMBOL: convertToSymbol,
  JSON: convertToJson
}

export default function convertConfig (config: SvgConfig, type: SvgOutputType) {
  return convertMap[type](config)
}
